<?php
/*
 * 邮件群发类
 */
include("../config/config.inc.php");
include("../config/QuickMySQL.php");
include("../config/function.inc.php");
include("./../class/class.phpmailer.php");

class CCrontabSendEmailNotify
{
	public $mysql = null;
	public $lockfile = "";
	public $subject = "";
	public $body = "";
	public $from = "";
	public $name = "";
	public $smtp = "";
	public $usr = "";
	public $pwd = "";
	public $port = 0;
	/* 构造函数 */
	function __construct() {
		$this->mysql = new QuickMySQL();
		$this->lockfile = dirname(__FILE__) . "/../lock/crontab-sendemailnotify";
		if( isset($_GET["id"]) ){
			$id = $_GET["id"];
			$this->lockfile .= "-{$id}";
			$fp = fopen($this->lockfile, "w");
			if( !$fp ){
				$this->DbgPrint("打开文件{$this->lockfile}失败");
				return;
			}
			if( !flock($fp, LOCK_EX | LOCK_NB) ){
				$this->DbgPrint("锁定文件{$this->lockfile}失败");
				return;
			}
			$this->DbgPrint("启动邮件队列{$id}");
			try{
				$this->OnStartSend($id);
			} catch (Exception $e){
				DbgPrint($this->logfile, "发送邮件{$id}操作出现异常" . $e->getMessage());
			}
			$this->DbgPrint("完成邮件队列{$id}");
			// 退出
			flock($fp, LOCK_UN);
			fclose($fp);
			unlink($this->lockfile);
		} else {
			$this->DbgPrint("定时启动");
			$this->OnEnumSend();
		}
	}
	/* 枚举发送 */
	function OnEnumSend(){
		$sql = "select sm_to from t_sendemail_notify where sm_run = 1";
		$res = $this->mysql->Query($sql);
		while( $row = mysql_fetch_row($res) ){
			$this->OpenUrl($row[0]);
		}
		mysql_free_result($res);
	}
	/* 开始发送 */
	function OnStartSend($id){
		// 获取信息
		$sql = "select a.sm_to, a.sm_subject, a.sm_lastday, a.sm_cycle, a.sm_body, b.addr, b.name, "
			. " b.smtp, b.user, b.pwd, b.port from t_sendemail_notify as a left join t_email_list as b "
			. " on a.m_no = b.id where a.sm_to = '{$id}'";
		$res = $this->mysql->Query($sql);
		if( !($row = mysql_fetch_row($res)) ){
			$this->DbgPrint("找不到id为{$id}的数据");
			return;
		}
		$sm_to = $row[0];
		$this->subject = $row[1];
		$sm_lastday = (int)$row[2];
		$sm_cycle = (int)$row[3];
		$this->body = $row[4];
		$this->from = $row[5];
		$this->name = $row[6];
		$this->smtp = $row[7];
		$this->usr = $row[8];
		$this->pwd = $row[9];
		$this->port = (int)$row[10];
		mysql_free_result($res);
		// 发送邮件
		$this->mysql->Query("update t_sendemail_notify set sm_firstdt = now() where sm_to='{$id}' and sm_firstdt is null");
		$this->mysql->Query("update t_sendemail_notify set sm_lastdt = now() where sm_to='{$id}'");
		// 开始执行
		$sql = "select id, email,qq,name,license,curdate(),DATEDIFF(lastdt,now()) from {$sm_to} "
			. " where (datediff(now(), ifnull(promptdt,date_add(now(),interval -{$sm_cycle} day))) >= {$sm_cycle})"
			. " and (datediff(lastdt, now()) between 0 and {$sm_lastday})";
		$res = $this->mysql->Query($sql);
		while( $row = mysql_fetch_row($res) ){
			if( $this->SendEmail($row[1], $row[2], $row[3], $row[4], $row[5], $row[6]) ){
				$this->mysql->Query("update t_sendemail_notify set sm_success = sm_success + 1 where sm_to='{$id}'");
				$this->mysql->Query("update {$sm_to} set sem_s = sem_s + 1 where id = {$row[0]}");
			} else {
				$this->mysql->Query("update t_sendemail_notify set sm_failure = sm_failure + 1 where sm_to='{$id}'");
				$this->mysql->Query("update {$sm_to} set sem_f = sem_f + 1 where id = {$row[0]}");
				$this->DbgPrint("发送邮件到{$row[1]}失败");
			}
			$this->mysql->Query("update {$sm_to} set promptdt = now() where id = {$row[0]}");
			sleep(1);
		}
		mysql_free_result($res);
	}
	/* 启动文件 */
	function OpenUrl($id){
		$fp = fsockopen("localhost", "80", $errno, $error);
		if( $fp ){
			fputs($fp, "GET {$_SERVER['PHP_SELF']}?id={$id} HTTP/1.1\r\n");
			fputs($fp, "Host: localhost\r\n\r\n");
			fclose($fp);
		} else {
			$this->DbgPrint("启动{$url}失败: {$error}");
		}
		
	}
	/* 打印日志 */
	function DbgPrint($log){
		$path = dirname(__FILE__);
		$fp = fopen("{$path}/../log/crontab-sendemail.log", "a");
		if( !$fp )
			return;
		fputs($fp, date("[Y-m-d H:i:s]\t"));
		fputs($fp, preg_replace("/[\r\n]/i", " ", $log) . "\r\n");
		fclose($fp);
	}
	/* 发送邮件 */
	function SendEmail($email, $qq, $name, $license, $date, $lastdt){
		$body = str_replace("{QQ}", $qq, $this->body);
		$body = str_replace("{name}", $name, $body);
		$body = str_replace("{license}", $license, $body);
		$body = str_replace("{data}", $date, $body);
		$body = str_replace("{rest}", $lastdt, $body);
		$mail = new PHPMailer();
		$mail->CharSet = "UTF-8"; // 邮件编码
		$mail->Encoding = "base64";
		$mail->IsSMTP(); // 设定使用SMTP服务
		$mail->SMTPAuth = true;
		$mail->SMTPSecure = "ssh";
		$mail->Host = $this->smtp; // 邮箱主机
		$mail->Port = $this->port; // 端口号
		$mail->Username = $this->usr; // 用户名
		$mail->Password = $this->pwd; // 密码
		$mail->SetFrom($this->from, $this->name); // 设置发件人
		$mail->Subject = $this->subject; // 标题
		$mail->IsHTML(true);
		$mail->Body = eregi_replace("[\](.)",'\\1',$body);
		$mail->AddAddress($email);
		
		return $mail->Send();
		
	}
}

ignore_user_abort(true);
set_time_limit(0);
$cc = new CCrontabSendEmailNotify();
?>